//
//  LyricTools.m
//  MusicPlayer
//
//  Created by lanou3g on 16/5/12.
//  Copyright © 2016年 韩宏. All rights reserved.
//

#import "LyricTools.h"

static LyricTools *lyricTools = nil;
@implementation LyricTools

+ (LyricTools *)shareLyricHandle
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (lyricTools == nil) {
            lyricTools = [[LyricTools alloc] init];
        }
    });
    return lyricTools;
}

//懒加载
- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray = [[NSMutableArray alloc] init];
    }
    return _modelArray;
}

//初始化歌词
- (void)lyricWithStr:(NSString *)str
{
    //如果模型数组中有数据,将其清空
    if (self.modelArray.count) {
        [self.modelArray removeAllObjects];
    }
    //根据'\n'分割歌词
    if (str.length < 1) {
        return;
    }
    NSArray *lyricArray = [str componentsSeparatedByString:@"\n"];
    //再次分割
    for (NSString *string in lyricArray) {
        if (!string.length) {
            //如果字符串为空,跳出本次循环,进行下一次循环遍历
            continue;
        }
        //根据']'分割歌词
        NSArray *lyricArr = [string componentsSeparatedByString:@"]"];
        NSString *time = nil;
        
        if ([(NSString *)lyricArr.firstObject length]) {
            time = [(NSString *)lyricArr.firstObject substringFromIndex:1];
        }
        NSString *lyric = lyricArr.lastObject;
        //创建歌词对象模型
        LyricTools *lyricTools = [LyricTools new];
        lyricTools.lyricStr = lyric;
        lyricTools.time = [self timeFromString:time];
        [_modelArray addObject:lyricTools];
    }
    for (int i = 0 ; i < 3; i ++) {
        LyricTools *lyric = [[LyricTools alloc] init];
        lyric.lyricStr = @"";
        lyric.time = 0;
        [self.modelArray insertObject:lyric atIndex:i];
    }
    
}
//根据时间段确定下标
- (NSInteger) indexForTime:(CGFloat)time
{
    int index = 0;
    for (LyricTools *lyT in _modelArray) {
        if (lyT.time > time) {
            return index - 1 > 0 ? index - 1 : 0;
        }
        index ++;
    }
    return index - 1;
}

//将time转化为float型
- (CGFloat) timeFromString:(NSString *)string
{
    NSArray *array = [string componentsSeparatedByString:@":"];
    CGFloat time = [array.firstObject integerValue] * 60 + [array.lastObject floatValue];
    return time;
}

@end
